<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import servers from '@/utils/request'
import sidentify from '@/components/numsidentify.vue'

// 初始化
const router = useRouter()
const form = ref(null)
const save = ref(localStorage.getItem('rememberMe') === 'true')

// 数据绑定，初始化时从 localStorage 获取保存的账号密码
const formModel = reactive({
  account: localStorage.getItem('rememberedAccount') || '',
  password: localStorage.getItem('rememberedPassword') || '',
  captcha: ''
})

// 校验规则
const rules = reactive({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur'},
    {pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码需包含字母和数字', trigger: 'blur'}
  ]
})

// 验证码相关
const identifyCode = ref('')
const result = ref('')
const sidentifyRef = ref(null)

// 消息提示
const showMessage = (type, msg) => {
  if (type === 'success') {
    ElMessage.success(msg)
  } else if (type === 'error') {
    ElMessage.error(msg)
  }
}

// 提取登录请求函数
const handleLoginRequest = (formData) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在登录...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  return servers.post('/login', formData, {
    headers: {'Content-Type': 'application/json'},
    timeout: 5000
  })
  .then(response => {
    if (response.status >= 200 && response.status < 300) {
      sessionStorage.setItem('Authorization', response.data.token)
      router.push('/home')
      showMessage('success', response.data.msg)
    }
    loadingInstance.close()
  })
  .catch(error => {
    showMessage('error', '登录失败，请重试')
    loadingInstance.close()
  })
}
// 记住我功能
const handleRememberMe = () => {
  if (save.value) {
    localStorage.setItem('rememberMe', 'true')
    localStorage.setItem('rememberedAccount', formModel.account)
    localStorage.setItem('rememberedPassword', formModel.password)
  } else {
    localStorage.removeItem('rememberMe')
    localStorage.removeItem('rememberedAccount')
    localStorage.removeItem('rememberedPassword')
  }
}

// 刷新验证码
const refreshCode = () => {
  if (sidentifyRef.value) {
    sidentifyRef.value.generateIdentifyCode()
  }
}

// 更新验证码结果
const updateResult = (res) => {
  result.value = res
}

// 自动登录
onMounted(() => {
  if (localStorage.getItem('rememberMe') === 'true') {
    const savedAccount = localStorage.getItem('rememberedAccount')
    const savedPassword = localStorage.getItem('rememberedPassword')
    
    if (savedAccount && savedPassword) {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在自动登录...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      handleLoginRequest({
        account: savedAccount,
        password: savedPassword
      }).finally(() => loadingInstance.close())
    }
  }
})

// 登录函数
const login = () => {
  form.value.validate((valid, errors) => {
    if (valid) {
      if (formModel.captcha === '') {
        showMessage('error', '请输入验证码')
        return false
      }
      if (formModel.captcha === result.value) {
        handleRememberMe()
        handleLoginRequest({
          account: formModel.account,
          password: formModel.password
        })
      } else {
        showMessage('error', '验证码不正确')
        formModel.captcha = ''
        refreshCode()
        return false
      }
    }
  })
}

// 清除输入框，同时清除本地存储
const clear = () => {
  formModel.account = ''
  formModel.password = ''
  formModel.captcha = ''
  save.value = false
  localStorage.removeItem('rememberMe')
  localStorage.removeItem('rememberedAccount')
  localStorage.removeItem('rememberedPassword')
}
</script>

<template>
  <div class="login" @keyup.enter="login">
    <h1 class="title">PX-WMS</h1>
    <el-form ref="form" :model="formModel" :rules="rules">
      <el-form-item prop="account">
        <span slot="label" class="btt">
          <span style="color: #fff;font-size: 20px;">账&nbsp;&nbsp;&nbsp;号：</span>
        </span>
        <el-input v-model="formModel.account" placeholder="请输入账号" />
        <span style="color: red">（必填）</span>
      </el-form-item>

      <el-form-item prop="password">
        <span slot="label" class="btt">
          <span style="color: #fff;font-size: 20px;">密&nbsp;&nbsp;&nbsp;码：</span>
        </span>
        <el-input v-model="formModel.password" type="password" placeholder="请输入密码" show-password />
        <span style="color: red">（必填）</span>
      </el-form-item>

      <el-form-item prop="captcha">
        <span slot="label" class="btt">
          <span style="color: #fff;font-size: 20px;">验证码：</span>
        </span>
        <el-input v-model="formModel.captcha" placeholder="请输入验证码" class="captcha" />
        <div class="identifybox" @click="refreshCode">
          <sidentify ref="sidentifyRef" v-model:identifyCode="identifyCode" @update:result="updateResult"/>
        </div>
        <span class="code" @click="refreshCode">看不清？点击图片刷新</span>
      </el-form-item>

      <el-form-item prop="save">
        <span slot="label" class="btt">
          <span style="color: #fff;font-size: 20px;">记住我：</span>
        </span>
        <el-switch v-model="save" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="large" class="btn" @click="login">登录</el-button>
        <el-button type="info" size="large" class="btn" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="bg"></div>
</template>

<style scoped>
.bg {
  background: url('../assets/back.webp') no-repeat center center fixed;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}

.login {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -260px;
  margin-left: -300px;
  padding: 30px;
  width: 600px;
  height: 400px;
  background: #9cbdd29c;
  border-radius: 15px;
  border: 1px dashed #efefef;
  box-shadow: var(--el-box-shadow-dark);
}

.btt {
  width: 15%;
}

.el-input {
  width: 60%;
}

.el-input.captcha {
  width: 30%;
}

h1.title {
  text-align: center;
  color: #fff;
}

.el-form-item {
  margin-bottom: 30px;
}

.login :deep(.el-form-item__label) {
  color: #ecf5ff;
}

.btn {
  width: 49%;
  border-radius: 5px;
}

.btn:hover {
  border: 1px solid #eee;
}

.login :deep(.el-form-item__error) {
  margin-left: 90px !important;
}

.code {
  margin-left: 10px;
  color: #2c3e50;
  cursor: pointer;
  text-decoration: underline;
}

.code:hover {
  color: #fff;
}
</style>
